package com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.dao;

import com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.entity.CustomsDeclarationFile;
import org.joda.time.DateTime;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * @author Lianhong
 * @since 2021/11/30
 */
@Repository
public class CustomsDeclarationFileDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private String selectCustomsDeclarationFileSql = "SELECT file, storageTime FROM gd_cardhead_file WHERE entryId = ?";

    public CustomsDeclarationFile findByEntryId(String entryId) {
        return namedParameterJdbcTemplate.getJdbcOperations().queryForObject(selectCustomsDeclarationFileSql,
                new Object[]{entryId}, new BeanPropertyRowMapper<>(CustomsDeclarationFile.class));
    }

    private String insertCustomsDeclarationFileSql = "INSERT INTO gd_cardhead_file (entryId, file, storageTime) VALUES (:entryId, :file, :storageTime)";

    public void save(CustomsDeclarationFile customsDeclarationFile) {
        customsDeclarationFile.setStorageTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        this.namedParameterJdbcTemplate.update(this.insertCustomsDeclarationFileSql, new BeanPropertySqlParameterSource(customsDeclarationFile));
    }

    private String existsCustomsDeclarationFileSql = "SELECT count(1) FROM gd_cardhead_file WHERE entryId = ?";

    public boolean exists(String entryId) {
        Integer count = namedParameterJdbcTemplate.getJdbcOperations()
                .queryForObject(this.existsCustomsDeclarationFileSql, new Object[]{entryId}, Integer.class);
        return count != null && count > 0;
    }

    private String deleteCustomsDeclarationFileSql = "DELETE FROM gd_cardhead_file WHERE entryId = ?";

    public void delete(String entryId) {
        this.namedParameterJdbcTemplate.getJdbcOperations().update(this.deleteCustomsDeclarationFileSql, entryId);
    }
}
